$(function () {

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }


  $("#sub").click(function () {
    /**
     * 一般网络请求使用ajax
     * $.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
     */
    $.ajax({
        contentType: "application/json;charset=utf8",
      type: 'POST',
      url: "/login",
      data: JSON.stringify({
          userName: $("#name").val(),
          password: $("#pwd").val()
      }),
      success: function (data) {
        if (data === "success") {
            var d = new Date();
            d.setTime(d.getTime() + (2 * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = 'userName' + "=" + $("#name").val() + "; " + expires;
            var username = getCookie("userName");
            window.location.href = "/user-paper.html?userName=" + username;
            //window.location.href = "/user-paper.html?userName="+$("#name").val();
        }
        else if (data === "failed") {
            alert("用户名错误！");
        }
        else {
            alert("密码错误！");
        }
      },
      contentType: "application/json; charset=utf-8"
    });
  });

});


